<template>
  <div style="padding: 0 20px">
    <HuilanBasicToolbar style="margin-top: 0;">
      <el-tooltip class="item" effect="dark" :content="$t('knowledgeTest.searchDetectTip')" placement="top-start">
        <el-button type="primary" class="header-search" @click="detecte()" size="small" :disabled="disabledFalg">{{$t('knowledgeTest.detecte')}}</el-button>
      </el-tooltip>
    </HuilanBasicToolbar>
    <div v-if="showType==''||(showType == 'detecte' && data.length > 0)||showType=='search'">
      <HuilanBasicSearchbar
          :model="searchForm"
          :fields="searchList"
          @search="searchChange"
          @reset="searchReset"
      >
        <template v-slot:knowledgeType>
          <el-select
              v-model="searchForm.knowledgeType"
              placeholder="请选择任务类型"
              :style="{width: '100%'}"
              @change="searchChange"
          >
            <el-option :label="$t('knowledgeTest.allType')" value=""></el-option>
            <el-option :label="$t('knowledgeTest.fqaKnowledge')" value="FAQ"></el-option>
            <el-option :label="$t('knowledgeTest.tableKnowledge')" value="TABLE"></el-option>
          </el-select>
        </template>
        <template v-slot:selectInput>
          <div id="formContainer">
            <el-input v-model="searchForm.question" :placeholder="$t('knowledgeTest.inputStandard')"></el-input>
          </div>
        </template>
      </HuilanBasicSearchbar>
      <div>
        <HuilanBasicToolbar style="margin-top: 0;margin-bottom: 20px;">
          <el-button type="success" class="header-search" @click="handleCommand('batchSync')" size="small" v-if="searchForm.knowledgeType != ''">{{$t('knowledgeTest.batchSync')}}</el-button>
          <el-button class="header-search" @click="handleCommand('batchDelete')" size="small">{{$t('knowledgeTest.batchDelete')}}</el-button>
        </HuilanBasicToolbar>
        <avue-crud
            :option="option"
            :search.sync="search"
            :table-loading="loading"
            :data="data"
            ref="crud"
            v-model="form"
            @row-del="rowDel"
            @row-update="rowUpdate"
            @row-save="rowSave"
            :before-open="beforeOpen"
            :page.sync="page"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @on-load="onLoad"
            @refresh-change="refreshChange">
          <template v-slot:menu="scope">
            <HuilanBasicActionTool
                :actions="getRowActions(scope.row,scope.index,data)"
                @command="handleCommand($event, scope.row,scope.index)"
            />
          </template>
        </avue-crud>
      </div>
    </div>
    <div v-if="showType == 'detecte' && data.length == 0 && !disabledFalg" class="tip-img-error">
      <img :src="detectionErrorTipPng">
    </div>
  </div>
</template>
<script>
import {listKnowledge} from "@/api/kwRobot/knowledgeTest";
import {
  knowledgeCheck,
  knowledgeCheckDelete,
  knowledgeCheckSync,
  listKnowledgeCheck,
  checkStatus
} from "../../../api/kwRobot/knowledgeTest";
export default {
  data() {
    return {
      detectionErrorTipPng: require("@/assets/kwRobotAnswer/detectionErrorTip.png"),
      detectionSearchTipPng: require("@/assets/kwRobotAnswer/detectionSearchTip.png"),
      searchForm: {
        knowledgeType: '',
        question: '',
      },
      searchList: [
        {
          slot:'slot',
          prop:'knowledgeType'
        },
        {
          slot:'slot',
          prop:'selectInput'
        },
      ],
      finishedFlag: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 1,
      },
      option:{
        header: false,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        menuAlign: "center",
        border: false,
        index: false,
        selection: true,
        viewBtn: false,
        delBtn:false,
        editBtn: false,
        //dialogType: 'drawer',
        dialogClickModal: false,
        dialogWidth: "40%",
        dialogType: 'drawer',
        emptyText: this.$t("aicosCommon.notData"),
        dialogCustomClass: 'huilan-drawer-form',
        form: {},
        menuWidth: 100,
        column:[
          {
            label:this.$t('knowledgeTest.standard'),  //问题
            prop:'realName',
            overHidden:true,
            minWidth:100,
          },
          {
            label:this.$t('knowledgeTest.knowledgeType'),
            prop:'knowledgeType',
            overHidden:true,
            minWidth:100,
            formatter: (val) => {
              var showHtml = ''
              if( val.knowledgeType == 'FAQ') {
                showHtml = this.$t('knowledgeTest.fqaKnowledge')
              } else {
                showHtml = this.$t('knowledgeTest.tableKnowledge')
              }
              return showHtml
            }
          },
          {
            label:this.$t('knowledgeTest.aicc'),
            prop:'mysQuestionId',
            overHidden:true,
            minWidth:100,
            formatter: (val) => {
              var showHtml = ''
              if( val.mysQuestionId == ''||val.mysQuestionId === null) {
                showHtml = '<i class="el-icon-close" style="color: red;font-weight: 700">'
              } else {
                showHtml = '<i class="el-icon-check" style="color: green;font-weight: 700">'
              }
              return showHtml
            }
          },
          {
            label:this.$t('knowledgeTest.aicces'),
            prop:'esQuestionId',
            overHidden:true,
            minWidth:100,
            formatter: (val) => {
              var showHtml = ''
              if(val.knowledgeType == 'FAQ') {
                if((val.esQuestionId == ''||val.esQuestionId === null)) {
                  showHtml = '<i class="el-icon-close" style="color: red;font-weight: 700">'
                } else {
                  showHtml = '<i class="el-icon-check" style="color: green;font-weight: 700">'
                }
              } else {
                showHtml = '--'
              }
              
              return showHtml
            }
          },
          {
            label:this.$t('knowledgeTest.robotes'),
            prop:'robotQuestionId',
            overHidden:true,
            minWidth:100,
            formatter: (val) => {
              var showHtml = ''
              if( val.robotQuestionId == ''||val.robotQuestionId === null) {
                showHtml = '<i class="el-icon-close" style="color: red;font-weight: 700">'
              } else {
                showHtml = '<i class="el-icon-check" style="color: green;font-weight: 700">'
              }
              return showHtml
            }
          },
        ],
      },
      data:[],
      selectionList: [],
      time: null,
      showType: '',
      disabledFalg: false,
      disabled: false,
    }
  },
  methods: {
    onLoad() {
      var info = {
        questionContent: this.searchForm.question,
        knowledgeType: this.searchForm.knowledgeType,
        current: this.page.currentPage,
        size: this.page.pageSize
      }
      // if(this.searchForm.knowledgeType == 'FAQ') {
      //   this.$set(this.option.column[2],'hide',false)
      // } else {
      //   this.$set(this.option.column[2],'hide',true)
      // }
      listKnowledgeCheck(info).then(res=>{
        if(res.data.code == 200) {
          this.data = res.data.data.records
          this.page.total = res.data.data.total
        }
      })
    },

    //获取操作栏按钮
    getRowActions(row) {
      const map = {
        syncBtn: {
          name: this.$t('knowledgeTest.sync'), //查看
          command: 'rowSync',
        },
        delBtn: {
          name: this.$t('aicosCommon.delBtn'), //删除
          command: 'rowDel',
        },
      };
      //加入功能项判断权限使用的
      var list = [];
      if(row.mysQuestionId == '' || row.mysQuestionId === null) {
        list = ['delBtn']
      } else {
        list = ['syncBtn','delBtn',]
      }
      const actions =[];

      list.forEach(item=> {
        //有功能项在打开这个限制
        // if(this.permissionList[item]) {
        //   actions.push(map[item])
        // }

        actions.push(map[item])
      })
      return actions;
    },

    //按钮操作
    handleCommand(command,row) {
      if(command == 'rowSync') {
        var info = {
          knowledgeIds: row.id,
          knowledgeType: row.knowledgeType,
        }
        knowledgeCheckSync(info).then(res=>{
          if(res.data.code == 200) {
            this.$message({
              type: "success",
              message: this.$t('knowledgeTest.syncSuccessfulTips')
            })
            this.onLoad()
          }
        })
      } else if(command == 'rowDel') {
        var info = {
          knowledgeIds: row.id,
          knowledgeType: this.searchForm.knowledgeType,
        }
        this.$confirm(this.$t("knowledgeTest.delTip"), {
          confirmButtonText: this.$t("aicosCommon.confirmBtn"),
          cancelButtonText: this.$t("aicosCommon.cancelBtn"),
          type: "warning",
        }).then(() => {
          return knowledgeCheckDelete(info);
        }).then(() => {
          this.onLoad();
          this.$message({
            type: "success",
            message: this.$t("aicosCommon.deleteSuccessTip"),
          });
        });
      } else if(command == 'batchSync') {
        var delFlag = false
        var ids = []
        if(this.selectionList.length == 0) {
          this.$message({
            type: "warning",
            message: this.$t("aicosCommon.chooseDataTip"),
          });
          return
        }
        this.selectionList.forEach(item=> {
          ids.push(item.id)
          if(item.mysQuestionId == '' || item.mysQuestionId === null) {
            delFlag = true
          }
        })
        if(delFlag) {
          this.$message({
            type: "warning",
            message: this.$t("knowledgeTest.syncTip"),
          });
          return
        }
        var info = {
          knowledgeIds: ids.join(','),
          knowledgeType: this.searchForm.knowledgeType,
        }
        knowledgeCheckSync(info).then(res=>{
          if(res.data.code == 200) {
            this.$message({
              type: "success",
              message: this.$t('knowledgeTest.syncSuccessfulTips')
            })
            this.onLoad()
          }
        })
      } else if(command == 'batchDelete') {
        var ids = []
        if(this.selectionList.length == 0) {
          this.$message({
            type: "warning",
            message: this.$t("aicosCommon.chooseDataTip"),
          });
          return
        }
        this.selectionList.forEach(item=> {
          ids.push(item.id)
        })
        var info = {
          knowledgeIds: ids.join(','),
          knowledgeType: this.searchForm.knowledgeType,
        }
        this.$confirm(this.$t("knowledgeTest.delTip"), {
          confirmButtonText: this.$t("aicosCommon.confirmBtn"),
          cancelButtonText: this.$t("aicosCommon.cancelBtn"),
          type: "warning",
        }).then(() => {
          return knowledgeCheckDelete(info);
        }).then(() => {
          this.onLoad();
          this.$message({
            type: "success",
            message: this.$t("aicosCommon.deleteSuccessTip"),
          });
        });
      }
    },

    selectionChange(list) {
      this.selectionList = list;
    },

    searchChange() {
      this.page.currentPage = 1;
      this.showType='search'
      this.onLoad()
    },

    searchReset() {
      this.searchForm.question = ''
      this.searchForm.knowledgeType = ''
      this.page.currentPage = 1;
      this.showType='search'
      this.onLoad()
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.showType='search'
      this.onLoad()
    },

    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.showType='search'
      this.onLoad()
    },

    detecte() {
      knowledgeCheck({}).then(res=>{
        if(res.data.code == 200) {
          this.onLoad()
          this.disabledFalg = true
          this.startTimer(res.data.data)
          this.checkStatusNow(res.data.data)
          this.$message({
            type: "success",
            message: res.data.data
          })
        }
      })
    },

    checkStatusNow(data) {
      checkStatus({}).then(res=>{
        if(res.data.code == 200) {
          if(res.data.data) {
            this.disabledFalg = true
          } else {
            this.stopTimer()
            this.disabledFalg = false
            this.$message({
              type: "success",
              message: this.$t('knowledgeTest.detectionCompleted')
            })
            this.onLoad()
            this.showType='detecte'
          }
        }
      })
    },
    
    startTimer(data) {
      if (this.timerId) return; // 如果定时器已经运行，不再创建

      this.timerId = setInterval(() => {
        this.checkStatusNow(data)
      }, 3000); // 每秒增加计数器
    },

    stopTimer() {
      if (this.timerId) {
        clearInterval(this.timerId);
        this.timerId = null;
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.tip-img {
  width: 600px;
  text-align: center;
  margin-left: 30%;
}
.tip-img-error {
  width: 420px;
  text-align: center;
  margin: auto;
  button {
    margin-top: 10px;
  }
}
.search-tip {
  display: block;
  font-size: 14px;
  color: #c4c4c4;
  margin-top: -30px;
  margin-bottom: 20px;
}
</style>